package com.neusoft.databus.common.interactive.collect;

import com.neusoft.databus.common.bean.CommandBean;
import com.neusoft.databus.common.exception.ConfigErrorException;
import com.neusoft.databus.common.interactive.Interactive;
import com.neusoft.databus.common.parser.Parser;

/**
 * the abstract class of collector
 *
 * @author sunchf
 * @date 2019年1月4日 下午4:55:42
 */
public abstract class Collector<T> extends Interactive<T> {
    protected Parser parser;

    public Collector(final Parser parser) {
        this.parser = parser;
    }

    public CommandBean collect(final CommandBean command) throws Exception {

        this.doCollect(command);

        final long executedSuccessCount = command.getResourceBean().stream().mapToLong(it -> {
            return it.getMetrics().stream().filter(m -> m.isExecutedSuccess()).count();
        }).sum();
        if (executedSuccessCount == 0) {
            throw new ConfigErrorException("未采集到任何数据，指令配置可能有问题");
        }

        final long parseSuccessCount = command.getResourceBean().stream().mapToLong(it -> {
            return it.getMetrics().stream().filter(m -> m.isParseSuccess()).count();
        }).sum();

        if (parseSuccessCount == 0) {
            throw new ConfigErrorException("未解析到任何指标，指令解析配置可能有问题");
        }

        return command;
    }

    /**
     * the concrete collector must override this method <br />
     *
     * @param command command
     * @throws Exception
     */
    protected void doCollect(final CommandBean command) throws Exception {
        throw new ConfigErrorException("非法请求，子类未实现doCollect方法");
    }

    public CommandBean control(final CommandBean command) throws Exception {
        this.doControl(command);
        return command;
    }

    /**
     * the concrete collector must override this method <br />
     *
     * @param command command
     * @throws Exception
     */

    protected void doControl(final CommandBean command) throws Exception {
        throw new ConfigErrorException("非法请求，子类未实现doControl方法");
    }

}
